package com.hlw.springboot.controller;
import com.alibaba.fastjson.JSONObject;
import com.hlw.springboot.constants.UserConstants;
import com.hlw.springboot.entity.SysUser;
import com.hlw.springboot.mapper.SysUserMapper;
import com.hlw.springboot.util.DataResult;
import com.hlw.springboot.util.IpConfig;
import com.hlw.springboot.util.R;
import com.hlw.springboot.util.ToLayuiTableUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.codec.digest.DigestUtils;



@RestController
@RequestMapping("/sysUser")
public class SysUserController {
    @Resource
    private SysUserMapper sysUserMapper;


    /**
     *
     * 用户列表
     */
    @PostMapping("/layui")
    @ApiOperation(value = "layui列表")
    @RequiresPermissions("sys:user:query")
    public R layuiList(@RequestBody Map<String, Object> map) {
        ToLayuiTableUtil.toMysqlPage(map);
        ToLayuiTableUtil toLayuiTable = ToLayuiTableUtil.setMap(map);
        Map<String, Object> data = toLayuiTable.getData();
        List<SysUser> list = sysUserMapper.list(data, toLayuiTable.getPage(), toLayuiTable.getLimit());
        int count = sysUserMapper.count(data);
        return R.ok().put("code", 0).put("data", list).put("count", count);
    }

    /**
     * 编辑用户
         */
    @PostMapping(value = "/saveUser")
    public DataResult innserUser(@ModelAttribute("user") SysUser user) {
        SysUser currentuser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        if(user.getId()==null){
            int checkNum = sysUserMapper.checkUserName(user.getUsername());
            if(checkNum>0){
                return new DataResult(404,"该用户名已被使用");
            }else {
                //设置盐加密
                user.setSalt(DigestUtils.md5Hex(UUID.randomUUID().toString() + System.currentTimeMillis() + UUID.randomUUID().toString()));
                Object object = new SimpleHash("MD5", user.getPassword(), user.getSalt(), UserConstants.HASH_ITERATIONS);
                user.setPassword(object.toString());
                user.setCreatetime(new Date());
                user.setCreateuser(currentuser.getNickname());
                user.setLocalip(IpConfig.localIp());
                sysUserMapper.insert(user);
                return new DataResult(1, "保存成功");
            }
        }else{
            user.setUpdatetime(new Date());
            user.setUpdateuser(currentuser.getNickname());
            user.setLocalip(IpConfig.localIp());
            sysUserMapper.updateByPrimaryKeySelective(user);
            return new DataResult(1,"修改成功");
        }
    }

    /**
     * 添加用户时重复时提醒
     */
    @RequestMapping("/checkUsername")
    public DataResult checkUsername(String userName){
        int checkNum = sysUserMapper.checkUserName(userName);
        if(checkNum>0){
            return new DataResult(404,"该用户名已被使用");
        }else{
            return new DataResult(0,"恭喜，该用户名可正常使用");
        }
    }

    /**
     * 根据Id获取用户
     */
    @RequestMapping("/findById")
    public DataResult findById(int userId){
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        return new DataResult(1,sysUser);
    }

    /**
     * 修改用户使用状态
     */
    @PutMapping("/editStatusById")
    public DataResult checkUsername(int userID,byte status){
       int count= sysUserMapper.updateStatus(userID,status);
       if(count>0){
           return new DataResult(1,"操作成功");
       }else {
           return new DataResult(401,"操作失败");
       }

    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delUser")
    public DataResult delUser(int userId){
        SysUser sysUser =sysUserMapper.selectByPrimaryKey(userId);
        if(sysUser.getUsername().equals("admin")){
            return new DataResult(401,"该用户不准删除");
        }else{
            sysUserMapper.deleteByPrimaryKey(userId);
            return new DataResult(1,"删除成功");
        }
    }

    /**
     * 重置密码 初始密码为123456
     */
    @RequestMapping("/resetPass")
    public DataResult resetPass(@RequestBody String userId){
        JSONObject jsonObject = JSONObject.parseObject(userId);
        List userList= (List) jsonObject.get("userId");
        for(Object i:userList){
             SysUser sysUser =sysUserMapper.selectByPrimaryKey((Integer) i);
            String password = "123456";
            Object object = new SimpleHash("MD5", password, sysUser.getSalt(), UserConstants.HASH_ITERATIONS);
            sysUser.setPassword(object.toString());
            sysUserMapper.updateByPrimaryKey(sysUser);
        }
        return new DataResult(1,"重置密码成功");
    }

    /**
     * 根据用户Id获取角色
     */
    @RequestMapping("/findRoleIdByUId")
    public DataResult findRoleIdByUId(int uid){
        Integer roleId = sysUserMapper.findRoleIdByUId(uid);
        if(roleId !=null){
            return new DataResult(1,roleId);
        }else {
            return new DataResult(401);
        }
    }

    /**
     * 根据用户Id获取角色
     */
    @RequestMapping("/updateRole")
    public DataResult updateRid(int uid,int rid){
        int count = sysUserMapper.selectCountByUId(uid);
        if(count >0){
            Integer roleId = sysUserMapper.updateRoleByUId(uid,rid);
            return new DataResult(1,"操作成功");
        }
        if (count == 0) {
            Integer roleId = sysUserMapper.insertRoleByUId(uid,rid);
            return new DataResult(1,"操作成功");
        }
        return new DataResult(404,"操作失败！！！");
    }



    /**
     *验证密码是否正确
     */
    @RequestMapping("/checkPassword")
    public DataResult checkPassword(int userId,String oldPassword){
            SysUser sysUser =sysUserMapper.selectByPrimaryKey(userId);
            Object object = new SimpleHash("MD5", oldPassword, sysUser.getSalt(), UserConstants.HASH_ITERATIONS);
            System.out.println("加密后的密码："+object.toString());
            System.out.println("存在数据库的密码："+sysUser.getPassword());
            if(sysUser.getPassword().equals(object.toString())){
                return new DataResult(1,"密码正确");
            }else{

                return new DataResult(404,"原始密码错误");
            }
    }


    /**
     *首页修改密码
     */
    @RequestMapping("/updatePassword")
    public DataResult updatePassword(int userId,String userPassword){
        SysUser sysUser =sysUserMapper.selectByPrimaryKey(userId);
        Object object = new SimpleHash("MD5", userPassword, sysUser.getSalt(), UserConstants.HASH_ITERATIONS);
        sysUser.setPassword(object.toString());
        sysUserMapper.updateByPrimaryKey(sysUser);
        return new DataResult(1,"修改成功");
        }
    }



